package com.xhui.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 对全局异常进行拦截并处理(本质上是通过AOP的方式对Controller进行动态代理)
 * 只要一个类上被RestController、Controller注解，就会拦截对应的异常
 */
@RestControllerAdvice(annotations = {RestController.class, Controller.class})
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 进行异常处理
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.error(ex.getMessage());
        if(ex.getMessage().contains("Duplicate entry")){
            String[] split = ex.getMessage().split(" ");
            // 当新增username(唯一索引)已存在时，报错信息ex.getMessage(): Duplicate entry 'zhangsan' for key 'employee.idx_username'
            // split[2]: 'zhangsan'
            String msg = split[2] + "已存在";
            return R.error(msg);
        }
        return R.error("服务器繁忙，请稍后重试！");
    }

    /**
     * 自定义的异常处理
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex){
        log.error(ex.getMessage());

        return R.error(ex.getMessage());
    }

}
